import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface Post {
  id: number
  title: string
  excerpt: string
  content: string
  date: string
  category: string
  tags: string[]
  coverImage: string
  readTime: number
  author: string
  views: number
  likes: number
}

export interface BlogStats {
  totalPosts: number
  totalCategories: number
  totalTags: number
  totalViews: number
  totalLikes: number
}

export const useBlogStore = defineStore('blog', () => {
  // 状态
  const posts = ref<Post[]>([
    {
      id: 1,
      title: 'Vue3 Composition API 深度解析',
      excerpt: '深入探讨Vue3 Composition API的使用方法和最佳实践，帮助你更好地理解响应式系统的原理。',
      content: `
        <h2>引言</h2>
        <p>Vue3的Composition API是Vue框架的一次重大革新，它为我们提供了更灵活、更强大的组件逻辑组织方式。本文将深入探讨Composition API的核心概念和使用方法。</p>
        
        <h2>什么是Composition API？</h2>
        <p>Composition API是Vue3中新增的一种编写组件逻辑的方式，它允许我们使用函数来组织组件的逻辑，而不是依赖于选项式API中的选项。</p>
        
        <h3>核心优势</h3>
        <ul>
          <li><strong>更好的逻辑复用</strong>：可以将相关的逻辑提取到独立的函数中</li>
          <li><strong>更好的类型推导</strong>：TypeScript支持更加完善</li>
          <li><strong>更小的打包体积</strong>：tree-shaking支持更好</li>
          <li><strong>更灵活的逻辑组织</strong>：可以按功能而不是选项来组织代码</li>
        </ul>
        
        <h2>基本用法</h2>
        <p>让我们从一个简单的例子开始：</p>
        
        <pre><code>import { ref, computed, onMounted } from 'vue'

export default {
  setup() {
    const count = ref(0)
    const doubleCount = computed(() => count.value * 2)
    
    const increment = () => {
      count.value++
    }
    
    onMounted(() => {
      console.log('组件已挂载')
    })
    
    return {
      count,
      doubleCount,
      increment
    }
  }
}</code></pre>
        
        <h2>响应式系统</h2>
        <p>Composition API的核心是响应式系统，主要包括以下几个API：</p>
        
        <h3>ref()</h3>
        <p>ref用于创建响应式引用，可以包装任何类型的值：</p>
        
        <pre><code>const count = ref(0)
const message = ref('Hello')
const user = ref({ name: 'John', age: 30 })</code></pre>
        
        <h3>reactive()</h3>
        <p>reactive用于创建响应式对象：</p>
        
        <pre><code>const state = reactive({
  count: 0,
  message: 'Hello',
  user: { name: 'John', age: 30 }
})</code></pre>
        
        <h2>生命周期钩子</h2>
        <p>Composition API提供了对应的生命周期钩子：</p>
        
        <ul>
          <li>onMounted - 组件挂载后</li>
          <li>onUpdated - 组件更新后</li>
          <li>onUnmounted - 组件卸载后</li>
          <li>onBeforeMount - 组件挂载前</li>
          <li>onBeforeUpdate - 组件更新前</li>
          <li>onBeforeUnmount - 组件卸载前</li>
        </ul>
        
        <h2>组合函数</h2>
        <p>组合函数是Composition API的精髓，它允许我们提取和复用组件逻辑：</p>
        
        <pre><code>// useCounter.js
import { ref, computed } from 'vue'

export function useCounter(initialValue = 0) {
  const count = ref(initialValue)
  const doubleCount = computed(() => count.value * 2)
  
  const increment = () => count.value++
  const decrement = () => count.value--
  const reset = () => count.value = initialValue
  
  return {
    count,
    doubleCount,
    increment,
    decrement,
    reset
  }
}</code></pre>
        
        <h2>总结</h2>
        <p>Composition API为Vue3带来了更强大的组件逻辑组织能力。通过合理使用组合函数，我们可以创建更加模块化、可复用的组件逻辑。</p>
        
        <p>虽然Composition API的学习曲线相对较陡，但一旦掌握，它将大大提升我们的开发效率和代码质量。</p>
      `,
      date: '2024-01-15',
      category: '前端开发',
      tags: ['Vue3', 'JavaScript', '前端'],
      coverImage: 'https://picsum.photos/800/400?random=1',
      readTime: 8,
      author: '张三',
      views: 1250,
      likes: 89
    },
    {
      id: 2,
      title: 'TypeScript 高级类型技巧',
      excerpt: '分享一些TypeScript中实用的高级类型技巧，让你的代码更加类型安全和易于维护。',
      content: `
        <h2>引言</h2>
        <p>TypeScript作为JavaScript的超集，提供了强大的类型系统。本文将介绍一些高级类型技巧，帮助你更好地利用TypeScript的类型系统。</p>
        
        <h2>条件类型</h2>
        <p>条件类型是TypeScript中非常强大的特性，它允许我们根据条件选择不同的类型：</p>
        
        <pre><code>type NonNullable&lt;T&gt; = T extends null | undefined ? never : T

type Result1 = NonNullable&lt;string | number | null&gt; // string | number
type Result2 = NonNullable&lt;string[] | null | undefined&gt; // string[]</code></pre>
        
        <h2>映射类型</h2>
        <p>映射类型允许我们从一个类型创建另一个类型：</p>
        
        <pre><code>type Readonly&lt;T&gt; = {
  readonly [P in keyof T]: T[P]
}

type Partial&lt;T&gt; = {
  [P in keyof T]?: T[P]
}</code></pre>
        
        <h2>模板字面量类型</h2>
        <p>TypeScript 4.1引入了模板字面量类型，允许我们创建基于字符串的模式：</p>
        
        <pre><code>type EventName&lt;T extends string&gt; = \`\${T}Changed\`
type Concat&lt;S1 extends string, S2 extends string&gt; = \`\${S1}\${S2}\`

type T0 = EventName&lt;'foo'&gt; // 'fooChanged'
type T1 = Concat&lt;'Hello', 'World'&gt; // 'HelloWorld'</code></pre>
        
        <h2>总结</h2>
        <p>这些高级类型技巧可以帮助我们创建更加精确和安全的类型定义，提升代码的可维护性。</p>
      `,
      date: '2024-01-10',
      category: '编程语言',
      tags: ['TypeScript', '编程'],
      coverImage: 'https://picsum.photos/800/400?random=2',
      readTime: 12,
      author: '张三',
      views: 980,
      likes: 67
    },
    {
      id: 3,
      title: '现代CSS布局技术对比',
      excerpt: '对比Flexbox、Grid和传统布局方式，帮助你选择最适合的CSS布局方案。',
      content: `
        <h2>引言</h2>
        <p>现代CSS提供了多种强大的布局技术，包括Flexbox和Grid。本文将对比这些技术的优缺点，帮助你选择最适合的布局方案。</p>
        
        <h2>Flexbox布局</h2>
        <p>Flexbox是一维布局模型，适合处理行或列的布局：</p>
        
        <pre><code>.container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}</code></pre>
        
        <h3>优点</h3>
        <ul>
          <li>简单易用，学习曲线平缓</li>
          <li>适合一维布局</li>
          <li>浏览器支持良好</li>
        </ul>
        
        <h2>Grid布局</h2>
        <p>Grid是二维布局模型，可以同时处理行和列：</p>
        
        <pre><code>.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 1rem;
}</code></pre>
        
        <h3>优点</h3>
        <ul>
          <li>强大的二维布局能力</li>
          <li>精确的网格控制</li>
          <li>适合复杂布局</li>
        </ul>
        
        <h2>总结</h2>
        <p>选择布局技术时，需要考虑项目的具体需求和浏览器兼容性要求。</p>
      `,
      date: '2024-01-05',
      category: 'CSS',
      tags: ['CSS', '布局', '前端'],
      coverImage: 'https://picsum.photos/800/400?random=3',
      readTime: 6,
      author: '张三',
      views: 756,
      likes: 45
    },
    {
      id: 4,
      title: 'React vs Vue: 选择哪个框架？',
      excerpt: '详细对比React和Vue的特点，帮助你根据项目需求选择合适的前端框架。',
      content: `
        <h2>引言</h2>
        <p>React和Vue都是优秀的前端框架，但它们有不同的设计理念和适用场景。本文将详细对比这两个框架的特点。</p>
        
        <h2>学习曲线</h2>
        <p>Vue的学习曲线相对平缓，而React需要更多的JavaScript知识。</p>
        
        <h2>生态系统</h2>
        <p>React拥有更大的生态系统和社区支持。</p>
        
        <h2>性能表现</h2>
        <p>两者在性能方面都表现优秀，具体选择需要根据项目需求。</p>
      `,
      date: '2024-01-01',
      category: '前端开发',
      tags: ['React', 'Vue', '前端', '对比'],
      coverImage: 'https://picsum.photos/800/400?random=4',
      readTime: 10,
      author: '张三',
      views: 1890,
      likes: 123
    },
    {
      id: 5,
      title: 'Node.js 性能优化实践',
      excerpt: '分享Node.js应用性能优化的实用技巧，包括内存管理、异步处理等方面。',
      content: `
        <h2>引言</h2>
        <p>Node.js应用的性能优化是一个重要的话题。本文将分享一些实用的优化技巧。</p>
        
        <h2>内存管理</h2>
        <p>合理管理内存是性能优化的关键。</p>
        
        <h2>异步处理</h2>
        <p>充分利用Node.js的异步特性。</p>
      `,
      date: '2023-12-28',
      category: '后端开发',
      tags: ['Node.js', '性能优化', '后端'],
      coverImage: 'https://picsum.photos/800/400?random=5',
      readTime: 15,
      author: '张三',
      views: 634,
      likes: 38
    },
    {
      id: 6,
      title: 'Git 工作流程最佳实践',
      excerpt: '介绍Git分支管理、提交规范和工作流程的最佳实践，提高团队协作效率。',
      content: `
        <h2>引言</h2>
        <p>Git是现代软件开发中不可或缺的工具。本文将介绍Git工作流程的最佳实践。</p>
        
        <h2>分支策略</h2>
        <p>Git Flow和GitHub Flow是两种常用的分支策略。</p>
        
        <h2>提交规范</h2>
        <p>规范的提交信息有助于项目维护。</p>
      `,
      date: '2023-12-25',
      category: '开发工具',
      tags: ['Git', '版本控制', '工作流程'],
      coverImage: 'https://picsum.photos/800/400?random=6',
      readTime: 9,
      author: '张三',
      views: 445,
      likes: 29
    }
  ])

  const searchQuery = ref('')
  const selectedCategories = ref<string[]>([])
  const currentPage = ref(1)
  const postsPerPage = ref(6)

  // 计算属性
  const categories = computed(() => {
    const cats = new Set(posts.value.map(post => post.category))
    return Array.from(cats)
  })

  const tags = computed(() => {
    const allTags = posts.value.flatMap(post => post.tags)
    const uniqueTags = new Set(allTags)
    return Array.from(uniqueTags)
  })

  const filteredPosts = computed(() => {
    let filtered = posts.value

    // 搜索筛选
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      filtered = filtered.filter(post => 
        post.title.toLowerCase().includes(query) ||
        post.excerpt.toLowerCase().includes(query) ||
        post.tags.some(tag => tag.toLowerCase().includes(query))
      )
    }

    // 分类筛选
    if (selectedCategories.value.length > 0) {
      filtered = filtered.filter(post => selectedCategories.value.includes(post.category))
    }

    return filtered.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
  })

  const totalPages = computed(() => Math.ceil(filteredPosts.value.length / postsPerPage.value))

  const paginatedPosts = computed(() => {
    const start = (currentPage.value - 1) * postsPerPage.value
    const end = start + postsPerPage.value
    return filteredPosts.value.slice(start, end)
  })

  const latestPosts = computed(() => {
    return posts.value
      .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
      .slice(0, 3)
  })

  const blogStats = computed((): BlogStats => {
    return {
      totalPosts: posts.value.length,
      totalCategories: categories.value.length,
      totalTags: tags.value.length,
      totalViews: posts.value.reduce((sum, post) => sum + post.views, 0),
      totalLikes: posts.value.reduce((sum, post) => sum + post.likes, 0)
    }
  })

  // 方法
  const getPostById = (id: number) => {
    return posts.value.find(post => post.id === id)
  }

  const getPostsByCategory = (category: string) => {
    return posts.value.filter(post => post.category === category)
  }

  const getPostsByTag = (tag: string) => {
    return posts.value.filter(post => post.tags.includes(tag))
  }

  const incrementViews = (id: number) => {
    const post = posts.value.find(p => p.id === id)
    if (post) {
      post.views++
    }
  }

  const toggleLike = (id: number) => {
    const post = posts.value.find(p => p.id === id)
    if (post) {
      post.likes++
    }
  }

  const setSearchQuery = (query: string) => {
    searchQuery.value = query
    currentPage.value = 1
  }

  const setSelectedCategories = (categories: string[]) => {
    selectedCategories.value = categories
    currentPage.value = 1
  }

  const setCurrentPage = (page: number) => {
    currentPage.value = page
  }

  const addPost = (post: Omit<Post, 'id' | 'views' | 'likes'>) => {
    const newPost: Post = {
      ...post,
      id: Math.max(...posts.value.map(p => p.id)) + 1,
      views: 0,
      likes: 0
    }
    posts.value.unshift(newPost)
  }

  return {
    // 状态
    posts,
    searchQuery,
    selectedCategories,
    currentPage,
    postsPerPage,
    
    // 计算属性
    categories,
    tags,
    filteredPosts,
    totalPages,
    paginatedPosts,
    latestPosts,
    blogStats,
    
    // 方法
    getPostById,
    getPostsByCategory,
    getPostsByTag,
    incrementViews,
    toggleLike,
    setSearchQuery,
    setSelectedCategories,
    setCurrentPage,
    addPost
  }
}) 